package com.usdt.web.core.config;

import java.util.HashMap;
import java.util.Map;

import org.apache.commons.collections.map.HashedMap;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.usdt.common.exception.ServiceException;
import com.usdt.system.service.cp.RequestManageService;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;

@Component
@Slf4j
public class OpenApiInterceptor implements HandlerInterceptor {
	
	private final String ACCESS_TOKEN_PATH = "/api-v1/customer/getUserInfo"; 
	
	@Autowired
	private RequestManageService requestManageService;
	
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		
		// 在请求处理前设置一些信息
		String accessTokenId = request.getHeader("Access-Token-Id");
		String accessUserId = request.getHeader("Access-User-Id");
		
		log.info("**********Access-Token-Id："+accessTokenId);
		log.info("**********Access-User-Id："+accessUserId);
		if(StringUtils.isBlank(accessTokenId) && StringUtils.isBlank(accessUserId)) {
			throw new ServiceException("登录已过期，请重新登录", -1);
		}
		
		Boolean tmp = true;
		if(StringUtils.isNotBlank(accessTokenId)) {
			Map<String, Object> map = new HashMap<>();
			map.put("accessTokenId", accessTokenId);
			String resp = requestManageService.postMethod(ACCESS_TOKEN_PATH, map, String.class);
			log.info("拦截器校验用户信息resp:"+resp);
			JSONObject object = JSON.parseObject(resp);
			JSONObject data = object.getJSONObject("data");
			if(null!=data) {
				//throw new ServiceException("获取用户信息失败", -1);
				String userId = data.getString("userId");
				String currentDeptId = data.getString("currentDeptId");
				String userName = data.getString("userName");
				if(StringUtils.isNotBlank(userId) && StringUtils.isNotBlank(currentDeptId)) {
					//throw new ServiceException("获取用户信息失败", -1);
					request.setAttribute("currentUserId", userId);
					request.setAttribute("currentDeptId", currentDeptId);
					request.setAttribute("userName", userName);
					tmp = false;
				}
			}
		}
		
		if(tmp) {
			if(StringUtils.isBlank(accessUserId)) {
				throw new ServiceException("登录已过期，请重新登录", -1);
			}
			String[] split = accessUserId.split(",");
			String currentDeptId = split[0];
			String userId = split[1];
			if(StringUtils.isNotBlank(userId) && StringUtils.isNotBlank(currentDeptId)) {
				request.setAttribute("currentUserId", userId);
				request.setAttribute("currentDeptId", currentDeptId);
			}
		}
		
		return true;
	}

	/*@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, 
	                            Object handler, Exception ex) {
	     // 清理ThreadLocal以避免内存泄漏
	   //UserAndDeptUtils.threadLocalMessage.remove();
	 }*/
	
}
